"""
-- coding: utf-8 --
@Time : 2023/7/31
@Author : 张书译
@Describe:获取ini配置文件信息
"""

import configparser
import config
from Comm.unit.Logger import logger


class ReadIniFile:
    """
    获取配置文件ini
    """

    def __init__(self, path=config.config_ini):
        self.path = path
        self.ini = configparser.RawConfigParser()

    def load_ini(self):
        """
        读取配置文件
        :return:  self.ini
        """
        self.ini.read(self.path, encoding="utf-8")
        return self.ini

    def get_str(self, section, option):
        """
        读取配置文件字符串类型
        :return: value
        """
        cf = self.load_ini()
        try:
            value = cf.get(section, option)
        except Exception as e:
            logger.debug(e)
            value = None
        return value

    def fix_option(self, section, option, value):
        """修改配置文件"""
        cf = self.load_ini()
        if section not in cf.sections():
            self.add_section(section)
        cf.set(section, option, value)
        fide = open(self.path, "r+", encoding="utf-8")
        cf.write(fide)
        fide.close()

    def get_int(self, section, option):
        """
        读取配置文件int类型
        :return: value
        """
        return self.ini.getint(section, option)

    def get_float(self, section, option):
        """
        读取配置文件float类型
        :return: value
        """
        if self.ini:
            return self.ini.getfloat(section, option)

    def get_boolean(self, section, option):
        """
        读取配置文件bool类型
        :return: value
        """
        if self.ini:
            return self.ini.getboolean(section, option)

    def add_section(self, section):
        """新增section"""
        if self.ini:
            self.ini.add_section(section)
            self.ini.write(open(self.path, "w", encoding="utf-8"))

    def remove_section(self, section):
        """删除指定section"""
        if self.ini:
            self.ini.remove_section(section)
            self.ini.write(open(self.path, "w", encoding="utf-8"))

    def remove_option(self, section, option):
        """删除指定option"""
        if self.ini:
            self.ini.remove_option(section, option)
            self.ini.write(open(self.path, "w", encoding="utf-8"))


